package com.ywdnf.gomoku.model.chess;

import com.ywdnf.gomoku.util.Const;
import com.ywdnf.gomoku.util.IdUtils;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 游戏模型
 *
 * @author lss
 * @date 2019-06-25, Tue
 */
@Getter
@Setter
public class Game {

  private static Random r = new Random();
  /**
   * 游戏id
   */
  private String gameId;

  /**
   * 游戏名称
   */
  private String name;

  private Player player1;

  private Player player2;

  private Player creator;

  private List<Round> rounds;

  private Round currentRound;

  private int currentRoundSequence;

  private boolean hide;

  private long gmtCreated;


  private boolean aiGame = false;


  /**
   * 最后修改时间
   */
  private long lastModified;


  public void setCurrentRound(Round currentRound) {
    currentRoundSequence++;
    this.currentRound = currentRound;
    // 设置当前回合数
    currentRound.setSequence(currentRoundSequence);
    // 设置先手
    setFirst();
    // 设置当前落子的玩家
    currentRound.setCurOptPlayer(currentRound.getFirst());
    // 添加此回合到游戏
    addRound(currentRound);
  }

  public Game(String name, boolean hide) {
    this.gameId = IdUtils.specifyPrefixAndLengthId(Const.GAME_ID_PREFIX, null, Const.GAME_ID_LEN_WITHOUT_PREFIX)
        .toUpperCase();
    this.state = GameState.WAITING_FOR_START;
    this.name =
        StringUtils.isEmpty(name) ? Const.DEFAULT_GAME_NICK_PREFIX : name;
    rounds = new ArrayList<>();
    currentRoundSequence = 0;
    lastModified = System.currentTimeMillis();
    this.hide = hide;
    this.gmtCreated = System.currentTimeMillis();
  }

  public Game(String name, boolean hide, boolean aiGame) {
    this(name, hide);
    this.aiGame = aiGame;
  }

  public GameState state;

  public void addRound(Round round) {
    rounds.add(round);
  }

  private void setFirst() {
    boolean isPlayer1 = r.nextInt() % 2 == 0;
    Player first = isPlayer1 ? player1 : player2;
    // 随机先手, 人工干预如果一个用户连续两次以上先手
    if (rounds.size() >= Const.MAX_CONTINUE_FIRST) {
      int count = rounds.size();
      Player last1p = rounds.get(count - 1).getFirst();
      Player last2p = rounds.get(count - 2).getFirst();
      if (last1p.equals(last2p)) {
        // 已经连续两次先手
        if (last1p.equals(first)) {
          // 即将第三次连续先手，更换先手
          first = isPlayer1 ? player2 : player1;
        }
      }
    }
    currentRound.setFirst(first);
  }
}
